import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useAreaStore } from './area'

// 从本地存储初始化用户信息
const initUserInfo = () => {
  try {
    const stored = uni.getStorageSync('userInfo')
    if (stored) {
      return {
        role: stored.role || '',
        token: stored.token || '',
        userId: stored.userId || '',
        mobile: stored.mobile || '',
        nickname: stored.nickname || '',
        avatar: stored.avatar || '/static/img/default-avatar.jpeg',
        department: stored.department || '',
        modules: stored.modules || []
      }
    }
  } catch (error) {
    console.warn('读取本地存储失败:', error)
  }
  
  // 默认用户信息
  return {
    role: 'offsite',
    token: '',
    userId: '',
    mobile: '',
    nickname: '',
    avatar: '/static/img/default-avatar.jpeg',
    department: '',
    modules: []
  }
}

export const useGlobalStore = defineStore('global', () => {
  const userInfo = ref(initUserInfo())

  // 设置用户信息（登录后调用，同时保存到本地）
  const setUserInfo = async (data: object) => {
    userInfo.value = { ...userInfo.value, ...data }
    // 保存到本地存储
    try {
      uni.setStorageSync('userInfo', userInfo.value)
    } catch (error) {
      console.warn('保存用户信息到本地存储失败:', error)
    }
    
    // 登录成功后获取区域数据
    try {
      const areaStore = useAreaStore()
      await areaStore.fetchAreaData()
    } catch (error) {
      console.warn('获取区域数据失败:', error)
    }
  }

  // 获取当前角色
  const getRole = () => userInfo.value.role

  // 清空用户信息（登出时调用，同时清除本地存储）
  const clearUserInfo = () => {
    const defaultInfo = {
      role: '',
      token: '',
      userId: '',
      mobile: '',
      nickname: '',
      avatar: '',
      department: '',
      modules: []
    }
    userInfo.value = defaultInfo
    // 清除本地存储
    try {
      uni.removeStorageSync('userInfo')
    } catch (error) {
      console.warn('清除本地存储失败:', error)
    }
  }

  return {
    userInfo,
    setUserInfo,
    getRole,
    clearUserInfo
  }
})
